package com.atomscat.lottery.controller.wx;

import com.atomscat.lottery.service.ReceiveWeChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 请填写接口配置信息，此信息需要你有自己的服务器资源，填写的URL需要正确响应微信发送的Token验证，请阅读消息接口使用指南。
 * URL: http://x.x.x/api/wechat/portal/{appid}
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/wechat/portal/{appid}")
public class WxPortalController {
    private final WxMpService wxService;
    private final ReceiveWeChatService receiveWeChatService;

    /**
     * Handles GET requests for WeChat server authentication.
     *
     * This method is used to verify the server's authenticity by responding
     * to WeChat's token validation request. It checks the provided parameters
     * and validates the signature to ensure the request is legitimate.
     *
     * @param appid    The WeChat app ID.
     * @param signature The signature for verifying the request.
     * @param timestamp The timestamp of the request.
     * @param nonce     The nonce for verifying the request.
     * @param echostr   The echo string to be returned if the request is valid.
     **/
    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable String appid, @RequestParam(name = "signature", required = false) String signature, @RequestParam(name = "timestamp", required = false) String timestamp, @RequestParam(name = "nonce", required = false) String nonce, @RequestParam(name = "echostr", required = false) String echostr) {
        log.info("\n接收到来自微信服务器的认证消息：[{}, {}, {}, {}]", signature, timestamp, nonce, echostr);
        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        if (wxService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "非法请求";
    }

    /**
     * Handles POST requests from the WeChat server.
     *
     * @param appid        The WeChat app ID.
     * @param requestBody  The raw XML request body sent by WeChat.
     * @param signature    The signature for verifying the request.
     * @param timestamp    The timestamp of the request.
     * @param nonce        The nonce for verifying the request.
     * @param openid       The OpenID of the user sending the request.
     * @param encType      (Optional) The encryption type of the message.
     * @param msgSignature (Optional) The message signature for encrypted messages.
     * @return A response string to be sent back to the WeChat server.
     * @throws IllegalArgumentException If the app ID is not found or the request is invalid.
     */
    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String post(@PathVariable String appid, @RequestBody String requestBody, @RequestParam("signature") String signature, @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce, @RequestParam("openid") String openid, @RequestParam(name = "encrypt_type", required = false) String encType, @RequestParam(name = "msg_signature", required = false) String msgSignature) {
        log.debug("接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}]," + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ", openid, signature, encType, msgSignature, timestamp, nonce, requestBody);
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }
        if (!wxService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }
        return receiveWeChatService.receiveWeChatToMq(appid, requestBody, signature, timestamp, nonce, openid, encType, msgSignature);
    }


}
